﻿using DevExpress.Utils;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using BCL.BaseLib;
using BCL.BaseLib.Basics;
using BCL.Component;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;


namespace BCL.Main
{
    public partial class FrmMain : XtraForm, ICustom, IMainForm
    {
        // 按钮列表控件
        private IBList ibList;
        private Action1<Form> runing;
        private List<FunctionEntity> openfe;

        public List<FunctionEntity> OpenedFe
        {
            get { return openfe; }
            set { openfe = value; }
        }
        public event Action1<Form> RuningEventHandler
        {
            add { runing += value; }
            remove { runing -= value; }
        }

        /// <summary>
        /// 头部控件
        /// by ZhaoHuan 2019/2/22
        /// </summary>
        public BaseFunctionControl TopControl
        {
            get
            {
                if (panelControlTop.Controls.Count > 0)
                    return (BaseFunctionControl)panelControlTop.Controls[0];
                return null;
            }
            set
            {
                if (panelControlTop.Controls.Count > 0)
                    panelControlTop.Controls.Clear();
                value.Dock = DockStyle.Fill;
                panelControlTop.Controls.Add(value);
            }
        }

        public FrmMain()
        {
            BCLApplication.MainForm = this;
            InitializeComponent();
            openfe = new List<FunctionEntity>();
            this.tcMainTable.TabControlChanged += (fe, adds) => { if (adds > 0) openfe.Add(fe); else openfe.Remove(fe); };
            this.Functiones = null;
            SetMoreButton();
            LoadPage();
        }
        public FrmMain(List<FunctionEntity> fes)
        {
            BCLApplication.MainForm = this;
            InitializeComponent();
            openfe = new List<FunctionEntity>();
            this.tcMainTable.TabControlChanged += (fe, adds) => { if (adds > 0) openfe.Add(fe); else openfe.Remove(fe); };
            this.Functiones = fes;
            SetMoreButton();
            LoadPage();
        }

        public List<FunctionEntity> Functiones
        {
            get { return BCLApplication.AppFunTree; }
            set
            {
                if (value != null)
                    RegisteFunctions(value);
                else
                {
                    BCLApplication.AppFunMunes = null;
                    BCLApplication.AppFunTree = null;
                }
                if (ibList != null)
                    ibList.Init();
            }
        }

        /// <summary>
        /// 将用户发过来的菜单项注册到全局树形与离散的菜单
        /// </summary>
        /// <param name="feList"></param>
        private void RegisteFunctions(List<FunctionEntity> feList)
        {
            List<FunctionEntity> appFunMunes = new List<FunctionEntity>();
            if (feList != null)
            {
                foreach (var item in feList)
                    appFunMunes.AddRange(FunctionToList(item));
            }
            BCLApplication.AppFunMunes = appFunMunes;
            BCLApplication.AppFunTree = feList;
        }

        /// <summary>
        /// 将树形菜单转换成离散菜单
        /// </summary>
        /// <param name="fe"></param>
        /// <returns></returns>
        private List<FunctionEntity> FunctionToList(FunctionEntity fe)
        {
            List<FunctionEntity> list = new List<FunctionEntity>();
            list.Add(fe);
            if (fe.Items != null)
                foreach (var item in fe.Items)
                    list.AddRange(FunctionToList(item));
            return list;
        }


        /// <summary>
        /// 执行自定义功能
        /// </summary>
        /// <param name="form"></param>
        /// <param name="fe"></param>
        public bool FunctionInvoke(Form form, FunctionEntity fe)
        {
            if (fe == null)
                return true;
            switch (fe.AppCode)
            {
                case "-1":
                    //panelControl1.Visible = !panelControl1.Visible;
                    break;
                case "-2":
                    break;
            }
            return true;
        }
        /// <summary>
        /// Handles the Load event of the FrmMain control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void FrmMain_Load(object sender, EventArgs e)
        {
            pnLoading.Location = new Point((this.Width - pnLoading.Width) / 2, (this.Height - pnLoading.Height) / 2 - 20);
            if (runing != null)
                runing(this);
            pnLoading.Visible = false;
            pnTop.Visible = true;
            pcMain.Visible = true;
        }



        #region 菜单面板

        void ibList_VisibleChanged(object sender, EventArgs e)
        {
            ibList.Location = pcMain.Location;
        }

        #endregion

        #region 应用设置
        /// <summary>
        /// 设置更多按钮
        /// by ZhaoHuan
        /// </summary>
        private void SetMoreButton()
        {
            var btnStart = new BarButtonItem();
            btnStart.ActAsDropDown = true;
            btnStart.Caption = "应用中心";
            btnStart.Glyph = global::BCL.Main.Properties.Resources.more;
            btnStart.Id = 12;
            btnStart.Name = "btnStart1";
            btnStart.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnStart_ItemClick);
            btnStart.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barMenu.AddItem(btnStart);

            //菜单面板
            ibList = new IBList();
            ibList.Name = "IBList";
            ibList.Location = tcMainTable.Location;
            ibList.Visible = false;
            this.Controls.Add(ibList);
            ibList.VerticalScroll.Value = 0;
            ibList.BringToFront();
            ibList.VisibleChanged += ibList_VisibleChanged;
        }
        /// <summary>
        /// 重绘我的应用
        /// by ZhaoHuan
        /// </summary>
        public void ReLoadMyApp()
        {
            barMenu.ItemLinks.Clear();
            SetMoreButton();
        }

        public void OpenMenu()
        {
            ibList.Visible = !ibList.Visible;
        }

        /// <summary>
        /// 应用菜单点击事件
        /// by ZhaoHuan
        /// </summary>
        /// <param name="fe">The fe.</param>
        public void App_Click(FunctionEntity fe)
        {
            if (fe != null)
            {
                // 隐藏菜单面板
                if (ibList != null)
                    ibList.Visible = false;

                if (fe.FunctionType == FunctionType.Function && fe.Custom != null)
                    fe.Custom.FunctionInvoke(this, fe);
                if (fe.FunctionType == FunctionType.Control && fe.Control != null)
                {
                    #region 控件
                    if ((fe.Control.Setting & FunctionControlSetting.UserControl) != 0)
                    {
                        this.tcMainTable.FunctionInvoke(this, fe);
                    }
                    if ((fe.Control.Setting & FunctionControlSetting.ShowDialog) != 0 || (fe.Control.Setting & FunctionControlSetting.Show) != 0)
                    {
                        BaseShowControl sc = fe.Control as BaseShowControl;
                        if (sc != null)
                            if ((fe.Control.Setting & FunctionControlSetting.ShowDialog) != 0)
                                sc.ShowDialog(this);
                            else
                                sc.Show();
                    }
                    #endregion
                }

            }
        }
        /// <summary>
        /// 应用导航按钮点击事件
        /// by ZhaoHuan
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="ItemClickEventArgs"/> instance containing the event data.</param>
        private void bsi_ItemClick(object sender, ItemClickEventArgs e)
        {
            FunctionEntity fe = (FunctionEntity)e.Item.Tag;
            App_Click(fe);
        }
        private void btnStart_ItemClick(object sender, ItemClickEventArgs e)
        {
            ibList.Visible = !ibList.Visible;
        }

        #endregion

        #region 打开应用
        /// <summary>
        /// 打开应用
        /// by ZhaoHuan
        /// </summary>
        /// <param name="appCode">应用编码</param>
        /// <param name="path">Url地址不包含主机名</param>
        public void OpenApp(string appCode, string path = "")
        {

            if (!string.IsNullOrEmpty(path))
            {
                FunctionEntity fe = BCLApplication.AppFunMunes.FirstOrDefault(m => m.AppCode == appCode);
                if (fe == null)
                {
                    MessageBox.Show("没有打开此应用的权限!", "提示");
                    return;
                }
                Uri url = new Uri(fe.ItemParamter.ToString());
                FunctionEntity newFe =  CopyObject<FunctionEntity, FunctionEntity>.Copy(fe);
                newFe.ItemParamter = url.Scheme + "://" + url.Host + path;
                newFe.IsReload = true;
                App_Click(newFe);
            }
            else
            {

                FunctionEntity fe = BCLApplication.AppFunMunes.FirstOrDefault(m => m.AppCode == appCode);
                if (fe == null)
                {
                    MessageBox.Show("没有打开此应用的权限!", "提示");
                    return;
                }
                App_Click(fe);
            }

        }
        #endregion


        public void RefreshMessageStates()
        {
            //// 动态加载汇编
            //string path = "BCL.Form.Main.dll";
            //Assembly assembly = Assembly.Load(path);

            // 根据类型名得到Type
            Type type = TopControl.GetType();
            // 根据类型名得到
            object o = Activator.CreateInstance(type);
            type.InvokeMember("UpdateMessageIcon", BindingFlags.Default | BindingFlags.InvokeMethod, null, o, new object[] { });

        }

        #region 其他
        /// <summary>
        /// 加载需要随程序启动的项与主页
        /// </summary>
        private void LoadPage()
        {
            if (BCLApplication.AppFunMunes == null)
                return;
            foreach (FunctionEntity item in BCLApplication.AppFunMunes)
                if (item.StartLoad || item.Index)
                    App_Click(item);
            if (BCLApplication.AppFunMunes.Any(o => o.Index))
                tcMainTable.Select(BCLApplication.AppFunMunes.First(o => o.Index));
        }


        /// <summary>
        /// Tip
        /// </summary>
        /// <param name="bar"></param>
        /// <param name="title"></param>
        /// <param name="text"></param>
        private void AddTip(BarItem bar, string title, string text)
        {
            ToolTipTitleItem tip = new ToolTipTitleItem { Text = text, LeftIndent = 6 };
            ToolTipTitleItem tiptitle = new ToolTipTitleItem { Text = title };
            SuperToolTip stip = new SuperToolTip();
            stip.Items.Add(tiptitle);
            stip.Items.Add(tip);
            bar.SuperTip = stip;

        }
        /// <summary>
        /// 快捷键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_KeyDown(object sender, KeyEventArgs e)
        {
            
            //if (e.KeyData == (Keys.Control | Keys.F))
            if (BCLApplication.AppFunMunes == null)
                return;

            //如果快捷键冲突,只调中第一个
            //FunctionEntity fe = BCLApplication.AppFunMunes.FirstOrDefault(item=>item.HotKey == e.KeyData && item.Enabled);
            //if (fe != null)
            //    App_Click(fe);

            //执行别的绑定到当前快捷键下的应用和功能
            foreach (FunctionEntity item in BCLApplication.AppFunMunes)
                if (item.HotKey == e.KeyData && item.Enabled)
                    App_Click(item);
        }

        public void OpenFunction(FunctionEntity info)
        {
            if (info == null)
                return;
            App_Click(info);
        }

        public void OpenFunction(BaseFunctionControl control)
        {
            if (control == null)
                return;
            App_Click(control.Function);
        }


        public void CloseFunction(FunctionEntity info)
        {

        }


        public void Msg(FunctionEntity fe)
        {
            if (fe == null)
                return;
            if (fe.Custom != null)
                fe.Custom.FunctionInvoke(this, fe);
            if (fe.Control != null)
                fe.Control.ReloadData(fe.ItemParamter);
        }

        #endregion

        public BaseFunctionControl FootControl
        {
            get;
            set;
        }


        public Action RefreshAppList
        {
            get;
            set;
        }
    }
}
